package com.heima.user.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;

import java.util.Map;
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ResponseResult<Map<String, Object>> login(LoginDto dto) {
        //判断是否是游客登录
        if (StrUtil.hasEmpty(dto.getPhone(), dto.getPassword())) {
            //游客登录，返回id=0的token
            return ResponseResult.okResult(
                    MapUtil.<String, Object>builder()
                            .put("token", AppJwtUtil.getToken(0l))
                            .build()
            );
        }
        //正常用户登录，首先通过查询用户
        ApUser apUser = this.getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
        if (ObjectUtil.isEmpty(apUser)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST, "手机号不存在");
        }
        //用户存在，判断密码是否正确
        String salt = apUser.getSalt();
        String md5Password = DigestUtil.md5Hex(dto.getPassword() + salt);
        if (ObjectUtil.notEqual(md5Password, apUser.getPassword())) {
            //密码错误
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //用户隐私置为空
        apUser.setSalt(null);
        apUser.setPassword(null);
        //密码正确，返回token
        return ResponseResult.okResult(
                MapUtil.<String, Object>builder()
                        .put("token", AppJwtUtil.getToken(Convert.toLong(apUser.getId())))
                        .put("user",apUser)
                        .build());


    }




}
